/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.front.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import io.renren.common.utils.R;
import io.renren.modules.sys.shiro.ShiroUtils;

/**
 * 定时任务日志
 *
 * @author Mark sunlightcs@gmail.com
 */

@Controller
public class FrontController {
    
    @Autowired
    private Producer producer;
    
    @RequestMapping(value = {"/", "index.html", "index"})
    public String index(Model model) {
        model.addAttribute("type", "all");
        return "index";
    }
    
    @RequestMapping(value = "login.html")
    public String login(Model model) {
        return "login";
    }
    
    @ResponseBody
    @RequestMapping(value = "user/login", method = RequestMethod.POST)
    public R login(String username, String password, String captcha, Model model) {
        
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if(!captcha.equalsIgnoreCase(kaptcha)){
            return R.error("验证码不正确");
        }
        
        try{
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        }catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return R.error("账号或密码不正确");
        }catch (LockedAccountException e) {
            return R.error("账号已被锁定,请联系管理员");
        }catch (AuthenticationException e) {
            return R.error("账户验证失败");
        }
        
        return R.ok().put("status", 0).put("href", "../index");
    }
    
    @RequestMapping(value = "user/logout")
    public String logout(String username, String password, String captcha, Model model) {
        
        ShiroUtils.logout();
        return "index";
    }
    
    @RequestMapping(value = "front/{page}")
    public String front(@PathVariable("page") String page, Model model) {
        model.addAttribute("test", "test");
        
        Map<String, String> types = new HashMap<>();
        types.put("quiz", "提问");
        types.put("share", "分享");
        types.put("discuss", "讨论");
        types.put("suggest", "建议");
        types.put("notice", "公告");
        types.put("news", "动态");
        
        List<Map<String, String>> data = new ArrayList<>();
        Random random = new Random();
        int time = 0;
        Long l = new Date().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String timeStr = null;
        for(int i=0;i<20;i++) {
            Map<String, String> map = new HashMap<>();
            
            time += random.nextInt(100000); 
            if(time > 7 * 24 * 3600) {
                timeStr = sdf.format(new Date(l - time));
            }else if(time > 24 * 3600) {
                timeStr = "" + (time / (24 * 3600)) + "天前";
            }else if(time > 3600) {
                timeStr = "" + (time /3600) + "小时前";
            }else if(time > 60) {
                timeStr = "" + (time /60) + "分钟前";
            }else if(time > 5) {
                timeStr = "" + time + "秒前";
            }else {
                timeStr = "刚刚";
            }
            
            map.put("id", ""+i);
            map.put("type", types.get(page));
            map.put("title", "基于 layui 的极简社区页面模版");
            map.put("author", "张文海");
            map.put("time", timeStr);
            map.put("xunshan", "" + random.nextInt(100));
            map.put("reply", "66");
            map.put("status", i%2 == 0? "0":"1");
        
            map.put("top", i%2 == 0? "1":"0");
            
            
            data.add(map);
        }
        
        
        
        model.addAttribute("data", data);
        model.addAttribute("type", page);
        
        return "jie/index";
    }
    
    @RequestMapping(value = "front/{page}/{cond}")
    public String front_cond(@PathVariable("page") String page, @PathVariable("cond") String cond, Model model) {
        model.addAttribute("cond", cond);
        
        return front(page, model);
    }
    
    @RequestMapping(value = "jie/{page}")
    public String jie(@PathVariable("page") String page) {
        
        return "jie/" + page;
    }
    
    @RequestMapping(value = "common/{page}")
    public String common(@PathVariable("page") String page) {
        return "common/" + page;
    }
    
    @RequestMapping(value = "user/{page}")
    public String user(@PathVariable("page") String page, Model model) {
        
        String type = page;
        if("activate".equals(page)) {
            type = "set";
        }
        
        model.addAttribute("type", type);
        return "user/" + page;
    }
    
    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }
}
